import { defineStore } from 'pinia';
import { login, getUserInfo } from '@/api/home';
import { setToken, removeToken } from '@/utils/token';

export const useUserStore = defineStore('user', {
  state: () => ({
    name: '',
    phone: '',
    pkid: '',
    points: '',
    roomId: '',
    canAnswerFlag: false,
    answer: '',
    checkResultObj: {
      isCorrect: false,
      introStr: '',
      yourAnswer: '',
      correctAnswer: ''
    }
  }),

  actions: {
    // 用户登录
    async login(userInfo) {
      const { username, password } = userInfo;
      try {
        const response = await login({
          username: username.trim(),
          password
        });
        const { token } = response.data;
        this.token = token;
        setToken(token); // 持久化到本地存储
        return Promise.resolve();
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        const response = await getUserInfo();
        const { name, phone, pkid, points, roomId } = response.data;

        if (!response.data) {
          return Promise.reject('Verification failed, please Login again.');
        } else {
          this.name = name;
          this.phone = phone;
          this.pkid = pkid;
          this.points = points;
          this.roomId = roomId;
          return Promise.resolve(response.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 用户登出
    async logout() {
      try {
        await this.resetToken()
        return Promise.resolve();
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 重置令牌
    resetToken() {
      this._resetState();
      removeToken();
      return Promise.resolve();
    },

    // 私有方法：重置状态
    _resetState() {
      this.$reset(); // Pinia 提供的重置方法
    }
  }
});
